package com.hd.hdxgddcommon.custom;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Administrator on 2018/11/13.
 */

/**
 * 仅在生成市场的时候，生成一个二维码
 * 目前是同步的浏览器配置，因为需求不需要同时发送。
 * 以后需要同事生成大量二维码时可以改
 */
public class QrHttpHandler {
    private static String QR_BUILD_BASE_URL = "http://www.kuaizhan.com/common/encode-png?large=true&data=";
    private static CloseableHttpClient httpClient;
    private static Integer SHORT_CONNECTION_TIMEOUT = 10 * 1000; //设置请求超时10秒钟 根据业务调整
    private static Integer SHORT_SO_TIMEOUT = 10 * 1000; //设置等待数据超时时间10秒钟 根据业务调整
    public static RequestConfig NoContinuousOperationRequestConfig;//非持续操作，即登录，获取表读数

    public static void init() {
        httpClient = HttpClients.createDefault();
        //设置连接超时时间
        NoContinuousOperationRequestConfig = getSimpleRequestConfig(SHORT_CONNECTION_TIMEOUT, SHORT_SO_TIMEOUT);
    }


    public static RequestConfig getSimpleRequestConfig(int connTimeout, int soTimeout) {
        return RequestConfig.custom().setConnectionRequestTimeout(connTimeout).setSocketTimeout(soTimeout).build();
    }

    public static boolean download(String name, String url) {
        try {
            HttpGet get = new HttpGet(QR_BUILD_BASE_URL + url);
            CloseableHttpResponse execute = httpClient.execute(get);
            HttpEntity entity = execute.getEntity();
            InputStream content = null;
            FileOutputStream outputStream = null;
            content = entity.getContent();
            outputStream = new FileOutputStream(name);

            copyFile(content, outputStream);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static void copyFile(InputStream ins, FileOutputStream out) throws IOException {
        byte[] b = new byte[1024];
        int n = 0;
        while ((n = ins.read(b)) != -1) {
            out.write(b, 0, n);
        }
        if (ins != null) {
            ins.close();
            ins = null;
        }
        if (out != null) {
            out.close();
            out = null;
        }

    }
}
